/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.financial.web.incomeexpenditure;

import com.alibaba.fastjson.JSONValidator;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.ar.entity.Tar;
import com.jeesite.modules.ar.entity.TarDetail;
import com.jeesite.modules.ar.service.TarService;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.fixedexpense.FixedExpense;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.service.cars.TcarService;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.custom.enumInfo.warehourseEnum;
import com.jeesite.modules.financial.entity.incomeexpenditure.IncomeExpenditure;
import com.jeesite.modules.financial.entity.incomeexpenditure.IncomeExpenditureDetail;
import com.jeesite.modules.financial.entity.lettercredit.LetterCredit;
import com.jeesite.modules.financial.service.incomeexpenditure.IncomeExpenditureService;
import com.jeesite.modules.financial.service.lettercredit.LetterCreditService;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.payment.entity.Tap;
import com.jeesite.modules.payment.entity.TapDetail;
import com.jeesite.modules.payment.service.TapService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 收支明细单Controller
 *
 * @author LV
 * @version 2021-03-04
 */
@Controller
@RequestMapping(value = "${adminPath}/financial/incomeExpenditure")
public class IncomeExpenditureController extends BaseController {

    @Autowired
    private IncomeExpenditureService incomeExpenditureService;
    @Autowired
    private ServiceOrderService serviceOrderService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private TapService tapService;
    @Autowired
    private TarService tarService;
    @Autowired
    private LetterCreditService letterCreditService;
    @Autowired
    private TcarService tcarService;
    @Autowired
    private FixedExpenseService fixedExpenseService;

    /**
     * 获取数据
     */
    @ModelAttribute
    public IncomeExpenditure get(String incomeExpenditureId, boolean isNewRecord) {
        return incomeExpenditureService.get(incomeExpenditureId, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("financial:incomeExpenditure:view")
    @RequestMapping(value = {"list", ""})
    public String list(IncomeExpenditure incomeExpenditure, Model model) {
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listAccountRec", tarService.findList(new Tar()));// 应收单号
        model.addAttribute("listAccountPay", tapService.findList(new Tap()));// 应付单号
        Supplier supplierFOR = new Supplier();
        supplierFOR.setSupplierType(warehourseEnum.HAIWAIZIFANG.getCode()); // 海外资方
        model.addAttribute("listSupplierFOR", supplierService.findList(supplierFOR));
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        model.addAttribute("listUser", empUserService.findList(new EmpUser()));
        model.addAttribute("listExpenseItem", fixedExpenseService.findList(new FixedExpense()));
        model.addAttribute("tcarList", tcarService.findList(new Tcar()));
        model.addAttribute("incomeExpenditure", incomeExpenditure);
        return "modules/financial/incomeexpenditure/incomeExpenditureList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("financial:incomeExpenditure:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page < IncomeExpenditure > listData(IncomeExpenditure incomeExpenditure, HttpServletRequest request, HttpServletResponse response) {
        incomeExpenditure.setPage(new Page <>(request, response));
        Page < IncomeExpenditure > page = incomeExpenditureService.findPage(incomeExpenditure);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("financial:incomeExpenditure:view")
    @RequestMapping(value = "form")
    public String form(IncomeExpenditure incomeExpenditure, Model model) {
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listAccountRec", tarService.findList(new Tar()));// 应收单号
        model.addAttribute("listAccountPay", tapService.findList(new Tap()));// 应付单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        model.addAttribute("listExpenseItem", fixedExpenseService.findList(new FixedExpense()));
        model.addAttribute("tcarList", tcarService.findList(new Tcar()));
        for (IncomeExpenditureDetail detail : incomeExpenditure.getIncomeExpenditureDetailList()) {
            detail.setCarName(detail.getTcar().getCarName());
        }
        model.addAttribute("incomeExpenditure", incomeExpenditure);
        return "modules/financial/incomeexpenditure/incomeExpenditureForm";
    }

    /**
     * 查看表单详情
     */
    @RequiresPermissions("financial:incomeExpenditure:view")
    @RequestMapping(value = "detail")
    public String detail(IncomeExpenditure incomeExpenditure, Model model) {
        Double totalIncomeAmount = 0D; // 收入
        Double totalExpenditureAmount = 0D; // 支出
        for (IncomeExpenditureDetail detail : incomeExpenditure.getIncomeExpenditureDetailList()) {
            totalIncomeAmount = NumberUtils.add(totalIncomeAmount,detail.getIncomeAmount());
            totalExpenditureAmount = NumberUtils.add(totalExpenditureAmount,detail.getExpenditureAmount());
        }
        model.addAttribute("totalIncomeAmount",totalIncomeAmount);
        model.addAttribute("totalExpenditureAmount",totalExpenditureAmount);
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listAccountRec", tarService.findList(new Tar()));// 应收单号
        model.addAttribute("listAccountPay", tapService.findList(new Tap()));// 应付单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        model.addAttribute("listExpenseItem", fixedExpenseService.findList(new FixedExpense()));
        model.addAttribute("tcarList", tcarService.findList(new Tcar()));
        String userCode = UserUtils.getUser().getUserCode();
        IncomeExpenditure incomeExpenditure1 = incomeExpenditureService.get(incomeExpenditure.getIncomeExpenditureId());
        String userFlag = "0";
        if(userCode.equals(incomeExpenditure1.getCreateBy())){
            userFlag = "1";
        }
        incomeExpenditure.setUserFlag(userFlag);
        model.addAttribute("incomeExpenditure", incomeExpenditure);
        return "modules/financial/incomeexpenditure/incomeExpenditureDetail";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("financial:incomeExpenditure:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated IncomeExpenditure incomeExpenditure) {
        incomeExpenditureService.save(incomeExpenditure);
        return renderResult(Global.TRUE, text("保存收支明细单成功！"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("financial:incomeExpenditure:delete")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(IncomeExpenditure incomeExpenditure) {
        incomeExpenditureService.delete(incomeExpenditure);
        return renderResult(Global.TRUE, text("删除收支明细单成功！"));
    }

    /**
     * 列表选择对话框
     */
    @RequiresPermissions("financial:incomeExpenditure:view")
    @RequestMapping(value = "incomeExpenditureSelect")
    public String empUserSelect(IncomeExpenditure incomeExpenditure, String selectData, Model model) {
        String selectDataJson = EncodeUtils.decodeUrl(selectData);
        if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()) {
            model.addAttribute("selectData", selectDataJson);
        }
        model.addAttribute("IncomeExpenditure", incomeExpenditure);
        return "modules/financial/incomeexpenditure/incomeExpenditureSelect";
    }


    /**
     * 单据流传创建   信用证创建
     */
    @RequiresPermissions("financial:incomeExpenditure:edit")
    @RequestMapping(value = "createIncomeExpenditure")
    public String createIncomeExpenditure(LetterCredit letterCredit, Model model) {
        LetterCredit oldLetterCredit = letterCreditService.get(letterCredit.getLetterCreditId());
        IncomeExpenditure incomeExpenditure = new IncomeExpenditure();

        if (oldLetterCredit != null && oldLetterCredit.getServiceOrder() != null && oldLetterCredit.getCustomer() != null
                && oldLetterCredit.getSupplier() != null && oldLetterCredit.getForeignBusinessmen() != null) {
            // 服务订单
            incomeExpenditure.setServiceOrderId(oldLetterCredit.getServiceOrderId());
            // 客户名称
            Customer customer = new Customer();
            customer.setCustomerId(oldLetterCredit.getCustomer().getCustomerId());
            incomeExpenditure.setCustomer(customer);
            // 供应商名称
            incomeExpenditure.setSupplierId(oldLetterCredit.getInvestorId());
            // 外商名称
            incomeExpenditure.setForeignBusinessmenId(oldLetterCredit.getForeignBusinessmenId());
            // 外币币种
            incomeExpenditure.setCurrency(oldLetterCredit.getCurrency());
            // 服务订单列表
            List < ServiceOrderDetail > serviceOrderDetailList = serviceOrderService.get(oldLetterCredit.getServiceOrderId()).getServiceOrderDetailList();
            List < IncomeExpenditureDetail > incomeExpenditureDetailList = ListUtils.newArrayList();
            for (ServiceOrderDetail serviceOrderDetail : serviceOrderDetailList) {
                IncomeExpenditureDetail incomeExpenditureDetail = new IncomeExpenditureDetail();
                incomeExpenditureDetail.setCarId(serviceOrderDetail.getCarId());
                incomeExpenditureDetail.setCarName(serviceOrderDetail.getTcar().getCarName());
                incomeExpenditureDetail.setModel(serviceOrderDetail.getModel());
                incomeExpenditureDetail.setForeignCurrencyPrice(serviceOrderDetail.getAmount());
                incomeExpenditureDetail.setFrameNumber(serviceOrderDetail.getFrameNumber());
                incomeExpenditureDetail.setRowNumber(serviceOrderDetail.getRowNumber());
                incomeExpenditureDetailList.add(incomeExpenditureDetail);
            }
            incomeExpenditure.setIncomeExpenditureDetailList(incomeExpenditureDetailList);

            model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
            model.addAttribute("listAccountRec", tarService.findList(new Tar()));// 应收单号
            model.addAttribute("listAccountPay", tapService.findList(new Tap()));// 应付单号
            model.addAttribute("listCustomer", customerService.findList(new Customer()));
            model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
            model.addAttribute("listExpenseItem", fixedExpenseService.findList(new FixedExpense()));
            model.addAttribute("tcarList", tcarService.findList(new Tcar()));
            model.addAttribute("incomeExpenditure", incomeExpenditure);
            return "modules/financial/incomeexpenditure/incomeExpenditureForm";
        } else {
            return renderResult(Global.FALSE, text("未查找到服务订单的相关信息！"));
        }

    }

    /**
     * 收支明细 创建应收应付
     */
    @RequiresPermissions("ar:tar:edit")
    @PostMapping(value = "createYsYf")
    @ResponseBody
    @Transactional(readOnly=false)
    public String createYsYf(@RequestParam("incomeExpenditureId") String incomeExpenditureId) {
        IncomeExpenditure incomeExpenditure = incomeExpenditureService.get(incomeExpenditureId);
        if (incomeExpenditure != null) {
            ServiceOrder serviceOrder = serviceOrderService.get(incomeExpenditure.getServiceOrderId());
            // 应收
            if (StringUtils.isEmpty(incomeExpenditure.getAccountingReceivable())) {
                Tar ar = new Tar();
                ar.setCustomerId(incomeExpenditure.getCustomerId());
                ar.setDate(new Date());
                ar.setStatus1("1"); // 单据状态-待生效
                ar.setBillStatus("2"); // 审批状态-已提交
                ar.setServiceOrderId(incomeExpenditure.getServiceOrderId());
                ar.setCurrency(incomeExpenditure.getCurrency());
                ar.setParentBillType("incomeExpend");
                ar.setParentBillCode(incomeExpenditure.getIncomeExpenditureId());
                Double total = 0D;
                List < TarDetail > list = ListUtils.newArrayList();
                for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                    for (IncomeExpenditureDetail incomeExpenditureDetail : incomeExpenditure.getIncomeExpenditureDetailList()) {
                        if (serviceOrderDetail.getRowNumber().equals(incomeExpenditureDetail.getRowNumber())) {
                            TarDetail detail = new TarDetail();
                            detail.setRowNumber(serviceOrderDetail.getRowNumber());
                            detail.setBrand(serviceOrderDetail.getBrand());
                            detail.setArea(serviceOrderDetail.getArea());
                            detail.setModel(serviceOrderDetail.getModel());
                            detail.setCarId(serviceOrderDetail.getCarId());
                            detail.setFrameNumber(serviceOrderDetail.getFrameNumber());
                            detail.setExpenseItem(incomeExpenditure.getExpenseItem());
                            detail.setApAmount(incomeExpenditureDetail.getIncomeAmount());
                            total = NumberUtils.add(total, incomeExpenditureDetail.getIncomeAmount());
                            list.add(detail);
                        }
                    }
                }
                ar.setAmount(total);
                ar.setTarDetailList(list);
                tarService.save(ar);
                incomeExpenditure.setAccountingReceivable(ar.getArId());
            }
            // 应付
            if (StringUtils.isEmpty(incomeExpenditure.getAccountingPayable())) {
                Tap ap = new Tap();
                ap.setSupplierId(incomeExpenditure.getSupplierId());
                ap.setDate(new Date());
                ap.setStatus1("1"); // 单据状态-待生效
                ap.setBillStatus("2"); // 审批状态-已提交
                ap.setServiceOrderId(incomeExpenditure.getServiceOrderId());
                ap.setCurrency(incomeExpenditure.getCurrency());
                ap.setParentBillType("incomeExpend");
                ap.setParentBillCode(incomeExpenditure.getIncomeExpenditureId());
                Double total = 0D;
                List < TapDetail > list = ListUtils.newArrayList();
                for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                    for (IncomeExpenditureDetail incomeExpenditureDetail : incomeExpenditure.getIncomeExpenditureDetailList()) {
                        if (serviceOrderDetail.getRowNumber().equals(incomeExpenditureDetail.getRowNumber())) {
                            TapDetail detail = new TapDetail();
                            detail.setRowNumber(serviceOrderDetail.getRowNumber());
                            detail.setBrand(serviceOrderDetail.getBrand());
                            detail.setArea(serviceOrderDetail.getArea());
                            detail.setModel(serviceOrderDetail.getModel());
                            detail.setCarId(serviceOrderDetail.getCarId());
                            detail.setFrameNumber(serviceOrderDetail.getFrameNumber());
                            detail.setExpenseItem(incomeExpenditure.getExpenseItem());
                            detail.setApAmount(incomeExpenditureDetail.getExpenditureAmount());
                            total = NumberUtils.add(total, incomeExpenditureDetail.getExpenditureAmount());
                            list.add(detail);
                        }
                    }
                }
                ap.setTapDetailList(list);
                ap.setAmount(total);
                tapService.save(ap);
                incomeExpenditure.setAccountingPayable(ap.getApId());
            }
            incomeExpenditureService.update(incomeExpenditure);
            return renderResult(Global.TRUE, text("生成成功！"));
        } else {
            return renderResult(Global.FALSE, text("未查找到服务订单的相关信息！"));
        }
    }
}
